package {
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	
	[SWF(width="960",height="560")]
	public class TestDomain extends Sprite 
	{
		private var classList:Array;
		private var domain:ApplicationDomain;
		
		public function TestDomain()
		{
			var loader:Loader=new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler);
			loader.load(new URLRequest("resource/swf/beautifulPet.swf"));
		}
		
		private function completeHandler(event:Event):void 
		{
			classList = new Array();
			
			var bytes:ByteArray=LoaderInfo(event.target).bytes;
			bytes.endian=Endian.LITTLE_ENDIAN;
			bytes.position=Math.ceil(((bytes[8]>>>3)*4+5)/8)+12;
			while(bytes.bytesAvailable>2)
			{
				var head:int=bytes.readUnsignedShort();
				var size:int=head&63;
				if (size==63)size=bytes.readInt();
				if (head>>6!=76)
				{
					bytes.position+=size;
				}else 
				{
					head=bytes.readShort();
					for(var i:int=0;i<head;i++){
						bytes.readShort();
						size=bytes.position;
						while(bytes.readByte()!=0);
						size=bytes.position-(bytes.position=size);
						var clsName:String = bytes.readUTFBytes(size);
						classList.push(clsName);
						trace("加载的文件域中类名："+clsName);
					}
				}
			}
			
			domain = LoaderInfo(event.target).applicationDomain;
			instanceClass();
		}
		
		private function instanceClass():void
		{
			var i:uint = 0;
			for(i;i<classList.length;i++)
			{
				var cls:Class = domain.getDefinition(classList[i]) as Class;
				var mc:MovieClip = new cls();
				mc.x = 50 + Math.random()*860;
				mc.y = 50 + Math.random()*460;
				this.addChild(mc);
			}
		}
	}
}